package com.sky.controller.User;

import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.mapper.DishMapper;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController("userDishController")
@RequestMapping("/user/dish")
public class DishController {


    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("/list")
    public Result<List<DishVO>> list(Long categoryId){
        //定义redis缓存菜品的key
        String key = "dish_" + categoryId;
        List<DishVO> dishVOList =(List<DishVO>) redisTemplate.opsForValue().get(key);

        //判断redis中是否有菜品数据,如果缓存中有数据直接返回，无需再查找数据库
        if(dishVOList !=null && dishVOList.size()>0){
            return Result.success(dishVOList);
        }


        log.info("分类id:{}",categoryId);
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        //起售的菜品才会显示
        dish.setStatus(StatusConstant.ENABLE);

        List<DishVO> list = dishService.listWithFlavor(dish);
        //redis中没有菜品数据，向redis中添加数据
        redisTemplate.opsForValue().set(key,list);

        return Result.success(list);
    }

}
